package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.pojo.TbAddress;
import com.dongdongshop.pojo.TbAreas;
import com.dongdongshop.pojo.TbCities;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.AddRessService;
import com.dongdongshop.service.ProvincesService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("address")
public class AddRessController {

    @DubboReference
    private AddRessService addRessService;

    @DubboReference
    private ProvincesService provincesService;

    @RequestMapping("getAddressInfo")
    @ResponseBody
    public Result getAddressInfo(){
        try {
            Subject subject = SecurityUtils.getSubject();
            TbUser tbUser = (TbUser) subject.getPrincipal();
            List<TbAddress> addressList = addRessService.getAddressInfo(tbUser.getUsername());
            return Result.ok().setData(addressList);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);

        }
    }

    @RequestMapping("getCity")
    @ResponseBody
    public Result getCity(String provinceId){
        try {
            List<TbCities> cities = provincesService.getCity(provinceId);
            return Result.ok().setData(cities);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);

        }
    }

    @RequestMapping("getArea")
    @ResponseBody
    public Result getArea(String cityId){
        try {
            List<TbAreas> area = provincesService.getArea(cityId);
            return Result.ok().setData(area);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);
        }
    }

    @RequestMapping("saveAddress")
    @ResponseBody
    public Result saveAddress(TbAddress address){
        try {
            Subject subject = SecurityUtils.getSubject();
            TbUser tbUser = (TbUser) subject.getPrincipal();
            address.setUserId(tbUser.getUsername());
            addRessService.saveAddress(address);
            return Result.ok();
        }catch (Exception e) {
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);
        }
    }

    @RequestMapping("deleteAddress")
    @ResponseBody
    public Result deleteAddress(Long id){
        try {
            addRessService.deleteAddress(id);
            return Result.ok();
        }catch (Exception e) {
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);
        }
    }

}
